import { format, isToday, isTomorrow, isPast, isThisWeek } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { Briefcase, User, BookOpen, Activity, FileText } from 'lucide-react'

// 检查日期是否有效
const isValidDate = (date: any): date is Date => {
  return date instanceof Date && !isNaN(date.getTime())
}

export const formatDate = (date: Date | string | null | undefined): string => {
  if (!date) return '无日期'
  
  // 对于只有日期的字符串（如 "2025-08-29"），创建本地时间的日期对象
  let dateObj: Date
  if (typeof date === 'string') {
    // 检查是否是只有日期的格式 (YYYY-MM-DD)
    if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
      // 创建本地时间的日期对象，避免时区转换
      const [year, month, day] = date.split('-').map(Number)
      dateObj = new Date(year, month - 1, day)
    } else {
      dateObj = new Date(date)
    }
  } else {
    dateObj = date
  }
  
  if (!isValidDate(dateObj)) return '无效日期'
  
  if (isToday(dateObj)) return '今天'
  if (isTomorrow(dateObj)) return '明天'
  if (isThisWeek(dateObj)) return format(dateObj, 'EEEE', { locale: zhCN })
  return format(dateObj, 'M月d日', { locale: zhCN })
}

export const formatTime = (date: Date | string | null | undefined): string => {
  if (!date) return '无时间'
  
  const dateObj = typeof date === 'string' ? new Date(date) : date
  if (!isValidDate(dateObj)) return '无效时间'
  
  return format(dateObj, 'HH:mm')
}

export const formatDateTime = (date: Date | string | null | undefined): string => {
  if (!date) return '无日期'
  
  // 对于只有日期的字符串，创建本地时间的日期对象
  let dateObj: Date
  if (typeof date === 'string') {
    if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
      // 只有日期的情况，不显示时间
      const [year, month, day] = date.split('-').map(Number)
      dateObj = new Date(year, month - 1, day)
      if (!isValidDate(dateObj)) return '无效日期'
      return format(dateObj, 'M月d日', { locale: zhCN })
    } else {
      dateObj = new Date(date)
    }
  } else {
    dateObj = date
  }
  
  if (!isValidDate(dateObj)) return '无效日期'
  
  return format(dateObj, 'M月d日 HH:mm', { locale: zhCN })
}

export const getDateStatus = (date: Date | string | null | undefined): string => {
  if (!date) return 'text-text-secondary'
  
  // 对于只有日期的字符串，创建本地时间的日期对象
  let dateObj: Date
  if (typeof date === 'string') {
    if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
      const [year, month, day] = date.split('-').map(Number)
      dateObj = new Date(year, month - 1, day)
    } else {
      dateObj = new Date(date)
    }
  } else {
    dateObj = date
  }
  
  if (!isValidDate(dateObj)) return 'text-text-secondary'
  
  if (isPast(dateObj)) return 'text-error'
  if (isToday(dateObj)) return 'text-warning'
  return 'text-text-secondary'
}

export const getPriorityColor = (priority: string): string => {
  switch (priority) {
    case 'P0': return 'text-red-300 bg-red-500/20 border-red-500/30'
    case 'P1': return 'text-orange-300 bg-orange-500/20 border-orange-500/30'
    case 'P2': return 'text-yellow-300 bg-yellow-500/20 border-yellow-500/30'
    case 'P3': return 'text-green-300 bg-green-500/20 border-green-500/30'
    default: return 'text-gray-300 bg-gray-500/20 border-gray-500/30'
  }
}

export const getPriorityLabel = (priority: string): string => {
  switch (priority) {
    case 'P0': return '紧急'
    case 'P1': return '高'
    case 'P2': return '中'
    case 'P3': return '低'
    default: return '低'
  }
}

export const getCategoryIcon = (category: string) => {
  switch (category) {
    case 'work': return Briefcase
    case 'personal': return User
    case 'learning': return BookOpen
    case 'health': return Activity
    case 'other': return FileText
    default: return FileText
  }
}

export const getCategoryEmoji = (category: string): string => {
  switch (category) {
    case 'work': return '💼'
    case 'personal': return '👤'
    case 'learning': return '📚'
    case 'health': return '🏃'
    case 'other': return '📝'
    default: return '📝'
  }
}

export const getCategoryLabel = (category: string): string => {
  switch (category) {
    case 'work': return '工作'
    case 'personal': return '个人'
    case 'learning': return '学习'
    case 'health': return '健康'
    case 'other': return '其他'
    default: return '其他'
  }
}

export const cn = (...classes: (string | undefined | null | false)[]): string => {
  return classes.filter(Boolean).join(' ')
}

// 相对时间格式化函数
export function formatRelativeTime(date: Date | string): string {
  const now = new Date()
  const targetDate = typeof date === 'string' ? new Date(date) : date
  const diffInSeconds = Math.floor((now.getTime() - targetDate.getTime()) / 1000)
  
  if (diffInSeconds < 60) {
    return '刚刚'
  }
  
  const diffInMinutes = Math.floor(diffInSeconds / 60)
  if (diffInMinutes < 60) {
    return `${diffInMinutes}分钟前`
  }
  
  const diffInHours = Math.floor(diffInMinutes / 60)
  if (diffInHours < 24) {
    return `${diffInHours}小时前`
  }
  
  const diffInDays = Math.floor(diffInHours / 24)
  if (diffInDays < 7) {
    return `${diffInDays}天前`
  }
  
  const diffInWeeks = Math.floor(diffInDays / 7)
  if (diffInWeeks < 4) {
    return `${diffInWeeks}周前`
  }
  
  const diffInMonths = Math.floor(diffInDays / 30)
  if (diffInMonths < 12) {
    return `${diffInMonths}个月前`
  }
  
  const diffInYears = Math.floor(diffInDays / 365)
  return `${diffInYears}年前`
}

// 智能时间显示函数 - 结合相对时间和绝对时间
export function formatSmartTime(date: Date | string, showFullDate = false): string {
  const targetDate = typeof date === 'string' ? new Date(date) : date
  const now = new Date()
  const diffInDays = Math.floor((now.getTime() - targetDate.getTime()) / (24 * 60 * 60 * 1000))
  
  // 如果是今天或昨天，显示相对时间
  if (diffInDays === 0) {
    return formatRelativeTime(targetDate)
  } else if (diffInDays === 1) {
    return '昨天'
  } else if (diffInDays === -1) {
    return '明天'
  } else if (Math.abs(diffInDays) < 7) {
    // 一周内显示相对时间
    return formatRelativeTime(targetDate)
  } else {
    // 超过一周显示具体日期
    if (showFullDate) {
      return targetDate.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    } else {
      return targetDate.toLocaleDateString('zh-CN', {
        month: 'short',
        day: 'numeric'
      })
    }
  }
}

// 获取时间上下文信息
export function getTimeContext(createdAt: Date | string, dueDate?: Date | string): {
  timeSpan: string
  urgency: 'low' | 'medium' | 'high'
  context: string
} {
  const created = typeof createdAt === 'string' ? new Date(createdAt) : createdAt
  const due = dueDate ? (typeof dueDate === 'string' ? new Date(dueDate) : dueDate) : null
  
  const now = new Date()
  const dayMs = 24 * 60 * 60 * 1000
  const createdDiff = Math.floor((now.getTime() - created.getTime()) / dayMs)
  
  let timeSpan = ''
  let urgency: 'low' | 'medium' | 'high' = 'medium'
  let context = ''
  
  if (due) {
    // 注意：Math.floor 对负数会向下取整，例如 -0.2 -> -1，
    // 会导致“今天早些时候到期”被误判为“已过期1天”。
    // 这里使用 Math.trunc 使其向零取整，-0.2 -> 0。
    const dueDiff = Math.trunc((due.getTime() - now.getTime()) / dayMs)
    const totalSpan = createdDiff + dueDiff
    
    if (dueDiff < 0) {
      // 已过期
      timeSpan = `已过期${Math.abs(dueDiff)}天`
      urgency = 'high'
      context = '任务已超过截止时间'
    } else if (dueDiff <= 1) {
      // 今天或明天到期
      timeSpan = dueDiff === 0 ? '今天到期' : '明天到期'
      urgency = 'high'
      context = '任务即将到期'
    } else if (dueDiff <= 3) {
      // 3天内到期
      timeSpan = `${dueDiff}天后到期`
      urgency = 'medium'
      context = '任务即将到期'
    } else if (totalSpan <= 7) {
      // 一周内创建且即将到期
      timeSpan = `创建${createdDiff}天，${dueDiff}天后到期`
      urgency = 'medium'
      context = '短期任务'
    } else {
      // 长期任务
      timeSpan = `创建${createdDiff}天，${dueDiff}天后到期`
      urgency = 'low'
      context = '长期任务'
    }
  } else {
    // 无截止日期
    if (createdDiff <= 1) {
      timeSpan = '刚刚创建'
      urgency = 'medium'
      context = '新任务'
    } else if (createdDiff <= 7) {
      timeSpan = `创建${createdDiff}天`
      urgency = 'low'
      context = '近期任务'
    } else {
      timeSpan = `创建${createdDiff}天`
      urgency = 'low'
      context = '长期任务'
    }
  }
  
  return { timeSpan, urgency, context }
}
